package servlets;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import model.User;
import services.UserService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;

@WebServlet(urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        User user = new User();
        user.setActiveCode(UUID.randomUUID().toString());
        String reqJson = GetRequestJsonUtils.getRequestJsonString(req);
        JSONObject js = JSON.parseObject(reqJson);
        user.setUsername(js.getString("username"));
        user.setPassword(js.getString("password"));
        user.setEmail(js.getString("email"));
        user.setTelephone(js.getString("telephone"));

        try {
            new UserService().register(user);
            Response build= Response.build(ResponseCode.SUCCESS);
            resp.getWriter().write(JSON.toJSON(build).toString());
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            if (e.getMessage().indexOf("Duplicate entry")>-1){
                Response build= Response.build(ResponseCode.ERROR_DUPLICATE);
                resp.getWriter().write(JSON.toJSON(build).toString());
            }else {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
